package FenxiaoService

import (
	"context"
	"fmt"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
)

// HandleOrderConfirmTask 处理等待期订单改为已结算
func HandleOrderConfirmTask() {
	ctx := context.Background()
	var foList []*entity.FenxiaoOrder
	fmt.Println("----------  处理等待期订单改为已结算  ----------------")
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_order").Where(
		"`status` = 90 AND settle_accounts_at > 0 AND settle_accounts_at < unix_timestamp(now())").Scan(&foList)
	if err != nil {
		return
	}
	if foList == nil {
		return
	}
	if len(foList) < 1 {
		return
	}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		for _, item := range foList {
			_, err := tx.Model("fenxiao_order").Unscoped().Where(
				"`status` = 90 AND order_id = ?", item.OrderId).Update(g.Map{
				"status": 99,
			})
			if err != nil {
				return err
			}
			_, err = tx.Model("fenxiao_order_details").Unscoped().Where(
				"`status` = 90 AND order_id = ?", item.OrderId).Update(g.Map{
				"status": 99,
			})
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return
	}
}
